package com.qf.controller;

/**
 * @Author 程云
 * @Date 2019/12/11 8:46
 * 人生在世 代码二字
 */

import com.qf.entity.Business;
import com.qf.entity.Dept;
import com.qf.entity.User;
import com.qf.enums.OAExceptionEnum;
import com.qf.service.BusinessService;
import com.qf.service.DeptService;
import com.qf.service.UserService;
import com.qf.utils.R;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

/**
 * 出差Controller
 */
@Controller
@RequestMapping("/resource")
@Slf4j
public class BusinessController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private UserService userService;

    @Autowired
    private BusinessService businessService;

    //出差界面
    @GetMapping("/renshi/demo2/list")
    public String renshi(Model model){
        //获取到当前登录用户的信息
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("user",user);
        //查询所有部门
        List<Dept> depts = deptService.findAllDept();
        model.addAttribute("dept",depts);
        //查询所有用户信息
        List<User> list = userService.findAllUser();
        model.addAttribute("listuser",list);
        return "resource/renshi/demo2/list";
    }

    @PostMapping("/add-bus")
    @ResponseBody
    public ResultVO addBus(@Valid Business business, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【出差事件】 参数错误 msg = {},business = {}",msg,business);
            return R.error(OAExceptionEnum.INFO_PARAM_ERROR.getCode(),msg);
        }
        Integer count = businessService.add(business);
        if (count != 1){
            log.info("【出差事件】 申请失败 count = {}",count);
            return R.error(OAExceptionEnum.SHENGQING_SHIBAII.getCode(), OAExceptionEnum.SHENGQING_SHIBAII.getMsg());
        }
        return R.ok();
    }

    @GetMapping("/add")
    public String add(){
        return "resource/system/user/add";
    }
}
